﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.MessageCommand;
using D.Medicalcare.Write.API.Application.Commands.RegistrationCommand;
using D.Medicalcare.Write.API.Application.Handlers.MessageHandler;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.RegistrationHandler
{
    public class AddRegistrationHandler : IRequestHandler<AddRegistrationCommand, APIResult<Registration>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Registration> rrep;
        private readonly ILogger<AddRegistrationHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="logger">日志</param>
        public AddRegistrationHandler(IMapper mapper, IBaseRepository<Registration> rrep, ILogger<AddRegistrationHandler> logger)
        {
            this.mapper = mapper;
            this.rrep = rrep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public async Task<APIResult<Registration>> Handle(AddRegistrationCommand request, CancellationToken cancellationToken)
        {
            APIResult<Registration> result = new APIResult<Registration>();
            try
            {
                var map = mapper.Map<Registration>(request);
                map.Statue = "待就诊";
                map.RegistrationTime = DateTime.Now;
                map.UpdateReson = null;
                map.UpdateTime = null;
                var a = rrep.AddAsync(map).Result;
                if (a > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "预约挂号成功";
                    result.Data = map;
                    logger.LogInformation("预约挂号成功");
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "预约挂号失败";
                    result.Data = map;
                    logger.LogError("预约挂号失败");
                }


                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError("预约挂号异常" + ex.Message);
                throw;
            }
        }
    }
}
